// pages/confirmOrder/confirmOrder.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [{
      name: "智能摄像机台版1080p网络WiFi家用监控室内",
      pic: "../../icons/s44.png",
      price: "169",
      num: 1,
      totalPrice: "169",
      lastPrice: 169
    }],
    fee: "0",
    totalPrice: 169,
    lastPrice: 169,
    productId: 0,
    name: "",
    phone: "",
    address: "",
    price: 0,
    num: 1,
    area: "",
    internetAddress: [],
    shopCarOrder: [],
    orderId: 0,
    cartId: [],
    productId: 0,
    isCart: "0"
  },
  // 填写地址
  fillAddress: function() {
    wx.navigateTo({
      url: '../addressAdmin/addressAdmin',
    })
  },
  addressAdmin: function() {
    wx.navigateTo({
      url: '../address/address',
    })
  },
  // 获取地址
  address: function() {
    var that = this;
    var address = [];
    wx.showLoading({
      title: '正在加载中',
      mask: true
    })
    console.log(wx.getStorageSync("userId"));
    wx.request({
      url: 'https://www.xiaozheng8.com/addr/findAll',

      data: {
        userId: wx.getStorageSync("userId"),
      },
      method: 'post',
      success: function(res) {
        console.log(res),
          that.setData({
            internetAddress: res.data.data
          }),
          wx.hideLoading();
        console.log(that.data.internetAddress)
        that.getAddress();
      }
    });
    console.log(wx.getStorageSync("addressId"));


  },
  // 获取地址
  getAddress: function() {
    var that = this;
    wx.showLoading({
      title: '正在加载中',
      mask: true
    });
    var address = [];
    console.log(that.data.internetAddress != "");
    console.log(wx.getStorageSync("addressId"));
    if (wx.getStorageSync("addressId") != "" && wx.getStorageSync("addressId")!=undefined && that.data.internetAddress != "") {


      wx.request({
        url: 'https://www.xiaozheng8.com/addr/findAll',
        data: {
          userId: wx.getStorageSync("userId"),
        },
        method: 'post',
        success: function(res) {
          console.log(res)
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].addrId == wx.getStorageSync("addressId")) {
              address = res.data.data[i];
              console.log(address);
            }
          }
          console.log(address);
          that.setData({
            name: address.name,
            phone: address.phone,
            address: address.addr + address.area,
            area: address.area
          });
          console.log(that.data.address);
          wx.hideLoading()
        },
        fail: function(res) {},
        complete: function(res) {},
      })
    } else if (that.data.internetAddress != "") {
      wx.request({
        url: 'https://www.xiaozheng8.com/addr/findAll',
        data: {
          userId: wx.getStorageSync("userId"),
        },
        method: 'post',
        success: function(res) {
          console.log(res),
            that.setData({
              address: res.data.data[0].addr + res.data.data[0].area,
              area: res.data.data[0].area,
              name: res.data.data[0].name,
              phone: res.data.data[0].phone,
            });
          console.log(that.data.address);
          wx.hideLoading()
        }
      });
    } else {
      console.log(that.data.address)
      wx.hideLoading()
      that.setData({
        address: ""
      })
    }
  },
  // 立即购买
  buy: function() {
    // var that = this;
    // wx.request({
    //   url: 'https://www.xiaozheng8.com/shop/product/findById',
    //   method: "post",
    //   data: {
    //     productId: that.data.productId
    //   },
    //   success: function (res) {
    //     console.log(res);
    //     var data = [];
    //     data.push(res.data.data);
    //     console.log(data);
    //     var icons = [];
    //     console.log(icons);
    //     that.setData({
    //       orderList: data,
    //       price: data[0].price
    //     });
    //     console.log(that.data.orderList)
    //   },
    //   fail: function (res) {
    //     console.log(res)
    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    var that = this;
    var json = JSON.parse(unescape(options.json));
    console.log(json)
    this.setData({
      orderList: json,
      price: options.price
    });
    console.log(that.data.orderList);
    //  判断是否是购物车传来的数据
    this.setData({
      isCart: options.isCart
    })
    if (options.isCart == 0) {
      that.setData({
        productId: json[0].productId
      })
    } else {
      var cartId = [];
      var num = 0;
      for (var i = 0; i < json.length; i++) {
        cartId.push(json[i].cartId);
        num = json[i].productCount + num
      };
      console.log(num);
      console.log(cartId);
      that.setData({
        cartId: cartId,
        num: num
      })
    }

  },
  // 提交订单
  submit: function() {
    var that = this;
    console.log(that.data.address);
    if (that.data.address == "" || that.data.address == undefined) {
      wx.showModal({
        title: '提示',
        content: '请先填写地址再购买商品',
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../addressAdmin/addressAdmin',
            })
          }
        }
      })
    } else {
      wx.request({
        url: 'https://www.xiaozheng8.com/shop/order/findByUserId',
        method: "post",
        data: {
          userId: wx.getStorageSync("userId")
        },
        success: function(res) {
          console.log(res);

        }
      })
      // wx.request({
      //   url: 'https://www.xiaozheng8.com/shop/order/pay',
      //   method:"post",
      //   data:{

      //   },
      //   success:function(res){
      //     console.log(res);
      //   }
      // })
      if (that.data.isCart == 0) {
        wx.showLoading({
          title: '正在加载中',
          mask: true
        })
        wx.request({
          url: 'https://www.xiaozheng8.com/shop/product/buy',
          data: {
            userId: wx.getStorageSync("userId"),
            productId: that.data.productId,
            productCount: 1,
            userName: that.data.name,
            phone: that.data.phone,
            address: that.data.address
          },
          method: 'post',
          success: function(res) {
            console.log(res);
            that.setData({
              orderId: res.data.data.orderId
            })

            that.pay(that.data.orderId);

          }
        })
      } else if (that.data.isCart == 1) {
        console.log(that.data.cartId);
        wx.showLoading({
          title: '正在加载中',
          mask: true
        })
        wx.request({
          url: 'https://www.xiaozheng8.com/shop/cart/buy',
          method: "post",
          data: {
            cartIdList: that.data.cartId,
            userName: that.data.name,
            phone: that.data.phone,
            address: that.data.address,
            userId: wx.getStorageSync("userId")

          },
          success: function(res) {
            console.log(res);
            that.setData({
              orderId: res.data.data.orderId
            })
            that.pay(that.data.orderId);
          }
        })
      }
    }

  },
  pay: function(id) {
    var that = this;
    
    wx.request({
      url: 'https://www.xiaozheng8.com/shop/order/pay',
      method: "post",
      data: {
        orderId: id,
        // 虚假的价格
        // totalFee: 1
        // 真实的价格
        totalFee:that.data.price*100

      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          "appId": res.data.appId,
          'paySign': res.data.paySign,
          success: function(res) {
            console.log('success');
            wx.hideLoading();
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              // duration: 3000
            });
            console.log(that.data.orderId);
            wx.hideLoading();
            wx.showToast({
                title: '商品购买成功',
                duration: 2000,
                success: function() {
                  setTimeout(function() {

                    wx.redirectTo({
                      url: '../orderDetails/orderDetails?orderId=' + that.data.orderId,
                    });
                  }, 2000)
                }
              }),

              wx.request({
              url: 'https://www.xiaozheng8.com/shop/order/setStatus',
                method: "post",
                data: {
                  orderId: that.data.orderId,
                  status: 2
                }
              })
          },
          fail: function(res) {
            console.log(res);
            console.log("取消支付");
            wx.hideLoading();
            wx.showToast({
              title: '商品购买失败',
              icon:"none",
              success: function() {
                setTimeout(function() {
                  wx.reLaunch({ 
                    url: '../shopping/shopping',
                  })
                }, 2000)
              },
              
            });
             setTimeout(function() {
                  wx.switchTab({
                    url: '../shopping/shopping',
                  })
                }, 2000)
            wx.request({
              url: 'https://www.xiaozheng8.com/shop/order/setStatus',
              method: "post",
              data: {
                orderId: that.data.orderId,
                status: 1
              },

            })
          },complete:function(){
            wx.hideLoading();
          }
        })

      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.address();
    this.buy();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})